package com.example.demo.Controler.UserController;

import com.example.demo.Entity.User;
import com.example.demo.Service.UserService;
import com.example.demo.tool.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import static com.example.demo.Errno.ErrnoDef.ERRNO_SUCCESS;

/**
 * 登录Controller
 */

@RestController

public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private UserService userService;


    /**
     * 用户登录
     * @param req_map 请求对象
     * @return json串（字典），键值对：<br>
     * - errno：错误码 (0为无错误)<br>
     * - msg：错误信息 <br>
     * - token：java web token,前端用以写入header的authorization中的值
     */
    @RequestMapping("/api/login")
    public Map<String,Object> login(@RequestBody Map<String,String> req_map){
        Map<String,Object> map = new HashMap<>();
        String name = req_map.get("name");
        String passwd = req_map.get("password");
        User dbUser = userService.selectUserByname(name);
        if(dbUser == null){
            map.put("errno",1001);
            map.put("msg","用户不存在");
        }
        if (dbUser.getName().equals(name) &&
                dbUser.getPassword().equals(passwd) )
        {
            //logger.info("登录成功！生成token！");
            String token = JwtUtil.createToken(dbUser);
            map.put("errno", ERRNO_SUCCESS.getErrno());
            map.put("msg","登录成功");
            map.put("token",token);
            return map;
        }
        else{
            map.put("errno",1002);
            map.put("msg","用户名与密码不匹配");
            return map;
        }
        //return map;
    }
}
